/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : my_home.js                            
*  Description  : 마이홈
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-06-25  김효순    Created.  
*******************************************************************************/

jQuery(function($){
	// 내가만든 조인룸
	function clsMyJoinroomList()
	{
		this._HTMLDom = null;
		this.listData = null;
		
		this._init();
	}
	
	clsMyJoinroomList.prototype = {
		_init: function(){
			var $layer = $("div#container div.self_home_joinroom:eq(0)");
			$layer.find("li:first table").css("cursor", "pointer");
			
			var $btn = $layer.find("img[alt='조인완료'], img[alt='조인마감'], img[alt='진행중'], img[alt='참여취소']");
			$layer.find("li:first td:last").html($btn);
			
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("li:first").clone(true)
			}
			
			this.setList([]);
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setList: function(thisData){
			this.listData = thisData;
			this.display();
		}
		, setWriterInfo: function(key, thisData){
			for(var i=0;i<this.listData.length;i++){
				if(this.listData[i]["조인룸코드"]+"" == key+"") break;
			}
			
			if(i < this.listData.length){
				this.listData[i]["부킹장"] = thisData;
				this.displayWriter(i);
			}
		}
		, setJoinList: function(key, thisData){
			for(var i=0;i<this.listData.length;i++){
				if(this.listData[i]["조인룸코드"]+"" == key+"") break;
			}
			
			if(i < this.listData.length){
				this.listData[i]["참여자"] = thisData;
				this.displayJoin(i);
			}
		}
		, setApplyList: function(joinroomKey, thisData){
			for(var i=0;i<this.listData.length;i++){
				if(this.listData[i]["조인룸코드"]+"" == joinroomKey+"") break;
			}
			
			if(i < this.listData.length){
				this.listData[i]["신청자"] = thisData;
				this.displayApply(i);
			}
		}
		, display: function(){
			var thisClass = this;
			var $layer = this.$getLayer();
			var $element = this._HTMLDom["$element"];
			
			$layer.prev("article").hide();
			$layer.find("ul").hide();
			
			if(this.listData.length){
				$layer.find("ul").show();
				
				$layer.children("ul").empty();
				for(var i=0;i<this.listData.length;i++){
					$layer.children("ul").append($element.clone(true));
				}
				
				$layer.find(">ul>li").each(function(n){
					var d = thisClass.listData[n];
					
					$(this).find("td:eq(0) img").attr("src", _gf.getDefaultProfileImage());
					/*if(thisClass.listData[n]["비밀방"]) $(this).find("#idPriv:first").show();
					else $(this).find("#idPriv:first").hide();*/
					$(this).find("td.nickname").html(d["부킹장"]["닉네임"]);
					$(this).find("td.time").html(d["날짜"] + "(" +  d["요일"] + ") <span> " + d["시간"] + "</span>");
					$(this).find("td.id").html(d["골프장코스명"] + d["조인룸상태코드"]);
					$(this).find("td:eq(4)").html(d["홀"] + "H");
					$(this).find("td:eq(5)").html(_util.leftB(d["내용"], 75));
					
					$(this).find("ol.person").empty();
					for(var i=0;i<d["초대인원"];i++){
						$(this).find("ol.person").append("<li class='off'>" + (i+1) + "</li>");
					}
					$(this).find("span.offer").html(0);
					
					var bName = "";
					switch(d["조인룸상태코드"]){
						case "C":
							bName = "진행중";
							break;
						case "D":
							bName = "조인마감";
							break;
						case "E":
							bName = "조인완료";
							break;
					}
					
					//if(d["조인룸상태코드"] != "D" && d["내상태코드"] != "S") bName = "참여취소";
					
					$(this).find("td:last img").hide();
					$(this).find("td:last img[alt='" + bName + "']").show();
				});
			}else{
				$layer.prev("article").show();
			}
			
			
		}
		, displayWriter: function(n){
			var $layer = this.$getLayer();
			var $obj = $layer.find(">ul>li").eq(n);
			var d = this.listData[n]["부킹장"];
			
			$obj.find("td:eq(0) img").attr("src", _gf.filePath2Url(d["이미지"])).error(function(){
				$(this).attr("src", _gf.getDefaultProfileImage());
			});
			$obj.find("td.nickname").html(d["닉네임"]).hover(function(){
				_gf.showProfileLayer($(this), d, "left", 0, $(this).height());
			}, function(){
				_gf.closeProfileLayer();
			});
		}
		, displayApply: function(n){
			var $layer = this.$getLayer();
			var d = this.listData[n]["신청자"];
			
			$layer.find("ul>li:eq(" + n + ") span.offer").html(d.length).hover(function(){
				if(d.length) _gf.showMemberLayer($(this), d, "left", -30, ($(this).height() || 10));
			}, function(){
				_gf.closeMemberLayer();
			});
		}
		, displayJoin: function(n){
			var $obj = this.$getLayer().find(">ul>li:eq(" + n + ")");
			var thisClass = this;
			var d = this.listData[n]["참여자"];
			
			$obj.find("ol.person").hover(function(){
				if(d.length) _gf.showMemberLayer($(this), d, "left", 0, ($(this).height() || 10));
			}, function(){
				_gf.closeMemberLayer();
			}).find("li").filter(":lt(" + d.length + ")").removeClass("off").addClass("on");
		}
		, spinStart: function(){
			var $layer = this.$getLayer();
			
			$layer.find("li").hide();
			if($layer.find("div#tmpSpin").length == 0){
				$layer.append("<div id='tmpSpin' style='position:relative; width:700px; height:150px;'></div>");
			}
			$layer.find("div#tmpSpin").spin().show();
		}
		, spinEnd: function(){
			var $layer = this.$getLayer();
			
			$layer.find("div#tmpSpin").spin(false).hide();
			$layer.find("li").show();
		}
		, getKey: function(n){
			return this.listData[n]["조인룸코드"];
		}
		, isReadAble: function(n){
			if(this.listData[n]["내상태"] == "S" || this.listData[n]["내상태"] == "A" || this.listData[n]["내상태"] == "P") return true;
			
			if(this.listData[n]["비밀방"]) return false;
			
			return true;
		}
	}
	
	
	// 내가 참여한 조인룸
	function clsJoinroomList()
	{
		this._HTMLDom = null;
		this.listData = null;
		
		this._init();
	}
	
	clsJoinroomList.prototype = {
		_init: function(){
			var $layer = $("div#container div.self_home_joinroom:eq(1)");
			$layer.find("li:first table").css("cursor", "pointer");
			
			var $btn = $layer.find("img[alt='조인완료'], img[alt='조인마감'], img[alt='진행중'], img[alt='참여취소']");
			$layer.find("li:first td:last").html($btn);
			
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("li:first").clone(true)
			}
			
			this.setList([]);
		}
		, $getLayer: clsMyJoinroomList.prototype.$getLayer
		, setList: clsMyJoinroomList.prototype.setList
		, setWriterInfo: clsMyJoinroomList.prototype.setWriterInfo
		, setJoinList: clsMyJoinroomList.prototype.setJoinList
		, setApplyList: clsMyJoinroomList.prototype.setApplyList
		, display: clsMyJoinroomList.prototype.display
		, displayWriter: clsMyJoinroomList.prototype.displayWriter
		, displayApply: clsMyJoinroomList.prototype.displayApply
		, displayJoin: clsMyJoinroomList.prototype.displayJoin
		, spinStart: clsMyJoinroomList.prototype.spinStart
		, spinEnd: clsMyJoinroomList.prototype.spinEnd
		, getKey: clsMyJoinroomList.prototype.getKey
		, isReadAble: clsMyJoinroomList.prototype.isReadAble
	}

	// 서버통신
	function clsComm()
	{
		// 내가만든 조인룸
		this.myJoinroomRequest = null;
		this.myJoinroomList = null;
		
		// 내가 참여한 조인룸
		this.joinroomRequest = null;
		this.joinroomList = null;
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){
			this.myJoinroomRequest = {};
			this.myJoinroomList = [];
		}
		// 내가만든 조인룸
		, setMyJoinroomRequest: function(key, val){
			if(typeof key == "object") this.myJoinroomRequest = key;
			else this.myJoinroomRequest[key] = val;
		}
		, getMyJoinroomList: function(){
			var thisClass = this;
			
			this.myJoinroomList = [];
			//ajax
			var serviceName = "getMyJoinRoomList";
			var options = {
				
			}
			_gf.ajax({
				"sid": "JR001"
				, "servicename": serviceName
				, "listcount": this.myJoinroomRequest["페이지당수"]
				, "currpageno": this.myJoinroomRequest["페이지"]
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "전체수": ret["msp"]["contents"]["@totalcount"]
					, "Sort": "0001"
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					if(!items.length) items = new Array(items);
					for(var i=0;i<items.length;i++){
						var obj = items[i];
						
						thisClass.myJoinroomList.push({
							"조인룸코드": _util.nvl(obj["joinRoomSeq"])+""
							, "부킹장": {
								"아이디": _util.nvl(obj["bookUserId"])+""
								, "닉네임": _util.nvl(obj["nickName"])+""
								, "이미지": _util.nvl(obj["path"]) + _util.nvl(obj["saveFileNm"])+""
							}
							, "날짜": _util.nvl(obj["reserveDate"])
							, "시간": _util.nvl(obj["bookingTime"])+""
							, "요일": _util.nvl(obj["bookingDay"])+""
							, "골프장코스명": _util.nvl(obj["golfClubInfo"])+""
							, "홀": _util.nvl(obj["holeInfo"])+""
							, "내용": _util.nvl(obj["ment"])+""
							, "참여자": []
							, "신청자": []
							, "비밀방": (obj["openYn"] == "Y") ? false:true
							, "내상태코드": _util.nvl(obj["joinStatus"])+""
							, "조인룸상태코드": _util.nvl(obj["procStatus"])+""
							, "조인룸상태": _util.nvl(obj["procStatusNm"])+""
							, "초대인원":  _util.nvl(obj["invitCnt"], 0)
						});
					}
				}
				
				document.objControl.finishMyJoinroomList(res);
			});
		}
		, getMyJoinroomData: function(){
			return this.myJoinroomList;
		}
		// 내가 참여한 조인룸
		, setJoinroomRequest: function(key, val){
			if(typeof key == "object") this.joinroomRequest = key;
			else this.joinroomRequest[key] = val;
		}
		, getJoinroomList: function(){
			var thisClass = this;
			
			this.joinroomList = [];
			//ajax
			var serviceName = "getMyJoinRoomParticipant";
			var options = {
				
			}
			_gf.ajax({
				"sid": "US001"
				, "servicename": serviceName
				, "listcount": this.joinroomRequest["페이지당수"]
				, "currpageno": this.joinroomRequest["페이지"]
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "전체수": ret["msp"]["contents"]["@totalcount"]
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					if(!items.length) items = new Array(items);
					for(var i=0;i<items.length;i++){
						var obj = items[i];
						
						thisClass.joinroomList.push({
							"조인룸코드": _util.nvl(obj["joinRoomSeq"])+""
							, "부킹장": {
								"아이디": _util.nvl(obj["bookUserId"])+""
								, "닉네임": _util.nvl(obj["nickName"])+""
								, "이미지": _util.nvl(obj["path"]) + _util.nvl(obj["saveFileNm"])+""
							}
							, "날짜": _util.nvl(obj["reserveDate"])
							, "시간": _util.nvl(obj["bookingTime"])+""
							, "요일": _util.nvl(obj["bookingDay"])+""
							, "골프장코스명": _util.nvl(obj["golfClubInfo"])+""
							, "홀": _util.nvl(obj["holeInfo"])+""
							, "내용": _util.nvl(obj["ment"])+""
							, "참여자": []
							, "신청자": []
							, "비밀방": (obj["openYn"] == "Y") ? false:true
							, "내상태코드": _util.nvl(obj["joinStatus"])+""
							, "조인룸상태코드": _util.nvl(obj["procStatus"])
							, "조인룸상태": _util.nvl(obj["procStatusNm"])+""
							, "초대인원":  _util.nvl(obj["invitCnt"], 0)
						});
					}
				}
				
				document.objControl.finishJoinroomList(res);
			});
		}
		, getJoinroomData: function(){
			return this.joinroomList;
		}
		// 참여자
		, getJoinList: function(arg){
			var thisClass = this;
			
//			arg = {
//				"조인룸키": null
//			}

			//ajax
			var serviceName = "getMemberList";
			var options = {
				"joinRoomSeq": arg["조인룸코드"]
			}
			_gf.ajax({
				"sid":"JR001",
				"servicename":serviceName
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "객체": arg["객체"]
					, "조인룸코드": arg["조인룸코드"]
				}
				
				var aList = [];
				
				var items = ret["msp"]["contents"]["items"];
				
				if(items){
					if(!items.length) items = new Array(items);
					
					for(var i=0;i<items.length;i++){
						var obj = items[i];
						aList.push({
							"아이디": _util.nvl(obj["participantId"])
							, "닉네임": _util.nvl(obj["nickName"])
							, "이미지": _util.nvl(obj["path"]) + _util.nvl(obj["saveFileNm"])
						});
					}
				}
				
				res["리스트"] = aList;
				document.objControl.finishJoinList(res);
			});
		}
		// 신청자
		, getApplyList: function(arg){
			var thisClass = this;
			
//			arg = {
//				"조인룸키": null
//			}

			//ajax
			var serviceName = "getApplyMemberList";
			var options = {
				"joinRoomSeq": arg["조인룸코드"]
			}
			_gf.ajax({
				"sid":"JR001",
				"servicename":serviceName
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "객체": arg["객체"]
					, "조인룸코드": arg["조인룸코드"]
				}
				
				var aList = [];
				
				var items = ret["msp"]["contents"]["items"];
				
				if(items){
					if(!items.length) items = new Array(items);
					
					for(var i=0;i<items.length;i++){
						var obj = items[i];
						aList.push({
							"아이디": _util.nvl(obj["participantId"])
							, "닉네임": _util.nvl(obj["nickName"])
							, "이미지": _util.nvl(obj["path"]) + _util.nvl(obj["saveFileNm"])
						});
					}
				}
				
				res["리스트"] = aList;
				document.objControl.finishApplyList(res);
			});
		}
	}
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objMyJoinroomList = null;
		this.objMyJoinroomPage = null;
		this.objJoinroomList = null;
		this.objJoinroomPage = null;
	}
	
	clsControl.prototype = {
		_init: function(){
			this._preload();
			
			this.objComm = new clsComm();
			this.objMyJoinroomList = new clsMyJoinroomList();
			this.objMyJoinroomPage = new _gf.clsPaging($("div#container article.my_joinroom_list:eq(0) div:last"), 10, 10);
			this.objJoinroomList = new clsJoinroomList();
			this.objJoinroomPage = new _gf.clsPaging($("div#container article.my_joinroom_list:eq(1) div:last"), 10, 10);
			
			this._beforeStart();
			this._bind();
		}
		, _preload: function(){
			_gf.spinStart();
			
			$("ul.pagenum_area").wrap("<div />").remove();
			$("div.help_box").remove();
		}
		, _beforeStart: function(){
			var thisClass = this;
			
			
			$.ajax({
				url: _ROOT + "/js/mypage_common.js"
				, dataType: "script"
				, async: false
				, success: function(){
					
				}
				, error: function(){
					alert("error");
				}
			});
			
			_util.executeThread(function(){
				return (_gf.getMyInfoData());
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			});
		}
		, _bind: function(){
			var thisClass = this;
			
			this.objMyJoinroomList.$getLayer().on("click", "table", function(){
				var n = thisClass.objMyJoinroomList.$getLayer().find("table").index($(this));
				var k = thisClass.objMyJoinroomList.getKey(n);
				
				thisClass.goViewPage(k);
			});
			
			this.objJoinroomList.$getLayer().on("click", "table", function(){
				var n = thisClass.objJoinroomList.$getLayer().find("table").index($(this));
				var k = thisClass.objJoinroomList.getKey(n);
				
				thisClass.goViewPage(k);
			});
			
			// 페이지이동
			$(this.objMyJoinroomPage).bind("evtPageClick", function(){
				thisClass.objMyJoinroomList.spinStart();
				
				thisClass.objComm.setMyJoinroomRequest({
					"페이지": thisClass.objMyJoinroomPage.getPage()
					, "페이지당수": thisClass.objMyJoinroomPage.getCountPerPage()
				});
				thisClass.objComm.getMyJoinroomList();
			});
			
			// 페이지이동
			$(this.objJoinroomPage).bind("evtPageClick", function(){
				thisClass.objJoinroomList.spinStart();
				
				thisClass.objComm.setJoinroomRequest({
					"페이지": thisClass.objJoinroomPage.getPage()
					, "페이지당수": thisClass.objJoinroomPage.getCountPerPage()
				});
				thisClass.objComm.getJoinroomList();
			});
		}
		, _start: function(){
			// 나의 조인룸
			this.objMyJoinroomList.spinStart();
			this.objMyJoinroomPage.setPage(1);
			this.objComm.setMyJoinroomRequest({
				"페이지": 1
				, "페이지당수": this.objMyJoinroomPage.getCountPerPage()
			});
			this.objComm.getMyJoinroomList();
			
			// 내가 참여한 조인룸
			this.objJoinroomList.spinStart();
			this.objJoinroomPage.setPage(1);
			this.objComm.setJoinroomRequest({
				"페이지": 1
				, "페이지당수": this.objJoinroomPage.getCountPerPage()
			});
			this.objComm.getJoinroomList();
		}
		// 조인룸 완료
		, finishMyJoinroomList: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			this.objMyJoinroomList.spinEnd();
			
			var thisData = this.objComm.getMyJoinroomData();
			var pageData = ret["전체수"];
			var thisClass = this;
			
			this.objMyJoinroomList.setList(thisData);
			this.objMyJoinroomPage.setTotalCount(pageData);
			this.objMyJoinroomPage.display();
			
			for(var i=0;i<thisData.length;i++){
				// 작성자
				_gf.getMemberInfo({
					"아이디": thisData[i]["부킹장"]["아이디"]
					, "조인룸코드": thisData[i]["조인룸코드"]
					, "콜백": function(res, info, arg){
						thisClass.objMyJoinroomList.setWriterInfo(arg["조인룸코드"], info);
					}
				});
				
				// 참여자
				this.objComm.getJoinList({
					"객체": thisClass.objMyJoinroomList
					, "조인룸코드": thisData[i]["조인룸코드"]
				});
				
				// 신청자
				this.objComm.getApplyList({
					"객체": thisClass.objMyJoinroomList
					, "조인룸코드": thisData[i]["조인룸코드"]
				});
			}
		}
		// 내가 참여한 조인룸 완료
		, finishJoinroomList: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			this.objJoinroomList.spinEnd();
			
			var thisData = this.objComm.getJoinroomData();
			var pageData = ret["전체수"];
			var thisClass = this;
			
			this.objJoinroomList.setList(thisData);
			this.objJoinroomPage.setTotalCount(pageData);
			this.objJoinroomPage.display();
			
			for(var i=0;i<thisData.length;i++){
				// 작성자
				_gf.getMemberInfo({
					"아이디": thisData[i]["부킹장"]["아이디"]
					, "조인룸코드": thisData[i]["조인룸코드"]
					, "콜백": function(res, info, arg){
						thisClass.objJoinroomList.setWriterInfo(arg["조인룸코드"], info);
					}
				});
				
				// 참여자
				this.objComm.getJoinList({
					"객체": thisClass.objJoinroomList
					, "조인룸코드": thisData[i]["조인룸코드"]
				});
				
				// 신청자
				this.objComm.getApplyList({
					"객체": thisClass.objJoinroomList
					, "조인룸코드": thisData[i]["조인룸코드"]
				});
			}
		}
		// 참여자완료
		, finishJoinList: function(ret){
			ret["객체"].setJoinList(ret["조인룸코드"], ret["리스트"]);
		}
		// 신청자완료
		, finishApplyList: function(ret){
			ret["객체"].setApplyList(ret["조인룸코드"], ret["리스트"]);
		}
		// 조인룸 이동
		, goViewPage: function(q_seq){
			var szLink = _ROOT + "/booking/join_room_view01.html?q_seq=" + q_seq;
			
			var a = document.createElement("A");
			$(a).attr({
				"href": szLink
				, "id": "idPermissionLink"
			}).appendTo($("body"));
			a.click();
			$(a).remove();
		}
	}
	
	document.objControl = new clsControl();
	document.objControl._init();
});
